package com.cheng.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * Author: Cheng
 * Date: 2019/8/8
 * Time: 0:08
 * Description: 邮件发送
 */
@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sender; //发送地址

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 发送给单一的用户
     *
     * @param toMail
     * @param content
     */
    public void simpleSend(String toMail, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(toMail);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(sender); //确保发送邮件地址与认证地址，如果不一致， 一些邮箱服务器会退信
        this.mailSender.send(message);
    }

    /**
     * 隐藏邮箱关键字段
     * @param email
     * @return
     */
    public String encodeEmail(String email) {
        String pre = email.substring(0, email.indexOf("@"));
        String after = email.substring(email.indexOf("@"));
        int emailLength = pre.length();
        char[] chars = pre.toCharArray();
        if (emailLength > 1) {
            int half = emailLength / 2;
            for (int i = 0; i < chars.length; i++) {
                if (i >= half) {
                    chars[i] = '*';
                }
            }
            pre = String.valueOf(chars);
        } else {
            pre = "*";
        }
        return pre + after;
    }
}
